package cn.ds.fly.common;

import cn.ds.fly.utils.UUIDUtils;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;

/**
 * Created by lds on 2017/12/14.
 */
public abstract class BaseService<T extends BaseEntity> {

    @Autowired
    protected Mapper<T> mapper;

    public T findById(String id){
        if(StringUtils.isBlank(id)){
            return null;
        }
        return mapper.selectByPrimaryKey(id);
    }

    public boolean save(T entity){
        if(entity==null){
            return false;
        }
        if(StringUtils.isBlank(entity.getId())){
            entity.setId(UUIDUtils.generateShortUuid());
        }
        mapper.insert(entity);
        return true;
    }

    public boolean update(T entity){
        if(entity==null&&StringUtils.isBlank(entity.getId())){
            return false;
        }
        int result = mapper.updateByPrimaryKeySelective(entity);
        if(result>0){
            return true;
        }
        return false;
    }

    public boolean delete(String id){
        if(StringUtils.isBlank(id)){
            return false;
        }
        int result = mapper.deleteByExample(id);
        if(result>0){
            return true;
        }
        return false;
    }

    public List<T> list(int pageNum, int pageSize,T entity ){
        if(entity==null||pageNum<0||pageSize<0){
            return null;
        }
        PageHelper.startPage(pageNum, pageSize);
        return mapper.select(entity);
    }

}
